<?php
/*
+--------------------------------------------------------------------------
|   IKPHP [#RELEASE_VERSION#]
|   ========================================
|   By IKPHP Software
|   © 2013 - 2050 WeCenter. All Rights Reserved
|   http://www.ikphp.com
|   ========================================
|   Author: 小麦 <ikphp@sina.cn>
+---------------------------------------------------------------------------
*/
defined ( 'IN_IKPHP' ) or exit ( 'WebSite Access Denied' );
// 创建life运行文件
// 可以替换框架入口文件运行
// 建议绑定位置app_init
class action_bulid{
	public function run(&$params) {
		if(!defined('BUILD_LIFE_FILE')) return ;
		$iklife   =   C('RUNTIME_LIFE_FILE',null,RUNTIME_PATH.'ik~life.php');
		if(is_file($iklife)) return;
		$defs       =   get_defined_constants(TRUE);
		
		$content    =   '$GLOBALS[\'_beginTime\'] = microtime(TRUE);';
	    if(MEMORY_LIMIT_ON) {
            $content .= '$GLOBALS[\'_startUseMems\'] = memory_get_usage();';
        }	
        // 生成数组定义
        unset($defs['user']['BUILD_LIFE_FILE']);
        $content   .=   $this->buildArrayDefine($defs['user']);

        // 读取编译列表文件
        $filelist = array(
                IKPHP_PATH.'function/function_core.php',
                CLASS_PATH . 'class_system'.EXT,
                CLASS_PATH . 'class_hook'.EXT,
                CLASS_PATH . 'class_application'.EXT,   
                CLASS_PATH . 'class_memory'.EXT,   
                CLASS_PATH . 'memory/memory_file'.EXT,  
                CLASS_PATH . 'class_exceptions'.EXT,               
             	);  
	    
        // 编译文件
        foreach ($filelist as $file){
          if(is_file($file)) {
            $content   .= compile($file);
          }
        }
        // 处理IKPHP类的start方法
        $content  =  preg_replace('/\$runtimefile = RUNTIME_PATH(.+?)(if\(APP_STATUS)/','\2',$content,1);
        $content  .=  "\nIKPHP::addMap(".var_export(IKPHP::getMap(),true).");";
        $content  .=  "\nL(".var_export(L(),true).");\nC(".var_export(C(),true).');hook::import('.var_export(hook::get(),true).');IKPHP::start();';
        
        // 生成运行Lite文件
        file_put_contents($iklife,strip_whitespace('<?php '.$content));
	}
    // 根据数组生成常量定义
    private function buildArrayDefine($array) {
        $content = "\n";
        foreach ($array as $key => $val) {
            $key = strtoupper($key);
            $content .= 'defined(\'' . $key . '\') or ';
            if (is_int($val) || is_float($val)) {
                $content .= "define('" . $key . "'," . $val . ');';
            } elseif (is_bool($val)) {
                $val = ($val) ? 'true' : 'false';
                $content .= "define('" . $key . "'," . $val . ');';
            } elseif (is_string($val)) {
                $content .= "define('" . $key . "','" . addslashes($val) . "');";
            }
            $content    .= "\n";
        }
        return $content;
    }	
}